package com.woorigil.android.koreaflower.activity.product;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.woorigil.android.koreaflower.activity.R;
import com.woorigil.android.koreaflower.activity.product.category.CategoryButton1OnClickListener;
import com.woorigil.android.koreaflower.activity.product.category.CategoryButton2OnClickListener;
import com.woorigil.android.koreaflower.activity.product.category.CategoryListFragment;
import com.woorigil.android.koreaflower.activity.product.list.ProductListAdapter;
import com.woorigil.android.koreaflower.domain.BeanFactory;
import com.woorigil.android.koreaflower.domain.product.DealDao;
import com.woorigil.android.koreaflower.domain.product.Product;
import com.woorigil.android.koreaflower.support.AlertUtils;
import com.woorigil.android.koreaflower.support.slidingmenu.SlidingMenu;

@SuppressLint("HandlerLeak") 
public class ProductListActivity extends ProductBaseActivity implements OnItemClickListener, OnScrollListener {
	private CategoryListFragment categoryListFragment1;
	private CategoryListFragment categoryListFragment2;
	
	private ListView productListView;
	private ProductListAdapter productListAdapter;
	protected boolean isAttachLock = false;
	protected boolean isMoreView = false;
	
	private ProgressDialog dataLoadingDialog;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.product_list_activity);
	
	        drawCategory();
	        drawBody();
	        getDataFromServer();
        } catch (Exception e) {
        	AlertUtils.errorAlert(this, null);
        }
    }
	
	private void drawCategory() {
        Button categoryButton1 = (Button)findViewById(R.id.category_button1);
        categoryButton1.setOnClickListener(new CategoryButton1OnClickListener(this));
        
        Button categoryButton2 = (Button)findViewById(R.id.category_button2);
        categoryButton2.setOnClickListener(new CategoryButton2OnClickListener(this));
        
		categoryListFragment1 = CategoryListFragment.newInstance(this);
		categoryListFragment2 = CategoryListFragment.newInstance(this);

		SlidingMenu slidingMenu = getSlidingMenu();
		slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
		slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
		slidingMenu.setShadowDrawable(R.drawable.shadow);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setFadeDegree(0.35f);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		
		slidingMenu.setSecondaryMenu(R.layout.category_body2);
		slidingMenu.setSecondaryShadowDrawable(R.drawable.shadowright);
		
		getSupportFragmentManager().beginTransaction().replace(R.id.category_framelayout1, categoryListFragment1).commit();
		setSlidingActionBarEnabled(false);
		setBehindContentView(R.layout.category_body1);

		getSupportFragmentManager().beginTransaction().replace(R.id.category_framelayout2, categoryListFragment2).commit();
		setSlidingActionBarEnabled(false);
	}
	
	private void drawBody() {
		productListView = (ListView) findViewById(R.id.product_list_view);
		productListAdapter = new ProductListAdapter(this, R.layout.product_list_row, new ArrayList<Product>());
		
		productListView.setAdapter(productListAdapter);
		productListView.setOnItemClickListener(this);
	}
	
    public void getDataFromServer() {
    	dataLoadingDialog = ProgressDialog.show(this, null, "데이터 수신중입니다.", true, false);

        Thread thread = new Thread(new Runnable() {
            public void run() {
            	Message msg = Message.obtain();
            	try {
            		msg.obj = BeanFactory.getBean(getApplicationContext(), DealDao.class).selectFreeDealList(1, 0, productListAdapter.getCount());
            	} catch (Exception e) {
            		msg.obj = e;
            	}
            	handler.sendMessage(msg);
            }
        });
        thread.start();
    }
    
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
	    	if (msg.obj instanceof Throwable) {
	    		alert((Exception)msg.obj);
	    		dataLoadingDialog.dismiss();
	    		return;
	    	}
	    	List<Product> productList = (List<Product>)msg.obj;
            drawDealListView(productList);
            dataLoadingDialog.dismiss();
        }
    };
    
	private void drawDealListView(List<Product> productList) {
		for (Product each : productList) {
			productListAdapter.add(each);
		}
		productListAdapter.notifyDataSetChanged();
	}    
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Product product = productListAdapter.getItem(position - productListView.getHeaderViewsCount());
		
		Intent intent = new Intent(this, ProductDetailActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.putExtra("product", product);
		startActivity(intent);
	}
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (isAttachLock) {
	    	return;
	    }
		
		if (productListView.getFooterViewsCount() > 0) {
			return;
		}
		
		if (totalItemCount > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
			isMoreView = true;
			getDataFromServer();
	    }  
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}	
	
    public void alert(Exception exception) {
        AlertUtils.errorAlert(this, exception);
    }

	public CategoryListFragment getCategoryListFragment1() {
		return categoryListFragment1;
	}
}
